﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class ObservablePropertyWrapper : AroundMethodBase, IAroundInvoke
	{
		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			if (!context.TargetMethod.Name.Contains("set_"))
				return;

			object thisObject = context.Target;
			string propInfoName = context.TargetMethod.Name.Substring(4);
			Type t = thisObject.GetType();
			PropInfo propInfo = t.GetPropInfo(propInfoName);
			ObservablePropertyAttribute[] attrs = propInfo.GetAttributes<ObservablePropertyAttribute>();

			if (attrs != null && attrs.Length > 0)
			{
				object oldValue = (when == CutpointType.Before) ? propInfo.GetValue(thisObject) : null;
				object newValue = context.Arguments[0];

				if (when == CutpointType.Before)
					attrs.ForEachAttribute(attr => attr.DoWorkBefore(context, propInfoName, thisObject, oldValue, newValue));
				else
					attrs.ForEachAttribute(attr => attr.DoWorkAfter(context, propInfoName, thisObject, returnValue));
			}
		}
	}
}

